<template>
  <div>
    <van-nav-bar title="登录" left-arrow @click-left="$router.go(-1)" />
    <van-form @submit="onSubmit">
      <van-field
        v-model="mobile"
        name="mobile"
        label="手机号"
        placeholder="请输入用户名"
        :rules="[
          { required: true, message: '请填写用户名' },
          {
            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '手机号格式不对'
          }
        ]"
      />
      <van-field
        v-model="code"
        type="text"
        name="code"
        label="验证码"
        placeholder="请输入验证码"
        :rules="[
          { required: true, message: '请输入验证码' },
          { pattern: /\d{6}/, message: '验证码格式不对' }
        ]"
      />
      <div style="margin: 16px;">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :disabled="isLoading"
          :loading="isLoading"
          loading-text="登录中..."
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { toLogin } from './user.js'
import { setToken } from '../../utils/token.js'
export default {
  name: 'login',
  data () {
    return {
      mobile: '13912345678',
      code: '246810',
      isLoading: false
    }
  },
  methods: {
    onSubmit (values) {
      this.isLoading = true
      toLogin(values)
        .then(res => {
          console.log(res)
          setToken(res.data.data)
          this.$toast.success('登陆成功')
          this.$router.push({ path: '/' })
        })
        .catch(err => {
          this.$toast.fail('登陆失败')
        })
        .then(() => {
          this.isLoading = false
        })
    }
  }
}
</script>

<style lang="less" scoped>
.van-nav-bar {
  background-color: #1a73e8;
  ::v-deep .van-nav-bar__content {
    .van-nav-bar__title {
      color: white;
    }
    .van-icon {
      color: white;
    }
  }
}
</style>
